package com.youth.hrsync.config.datasource;

import com.kcis.xian.hrsync.mapper.xian.XianCheckinoutMapper;
import com.kcis.xian.hrsync.mapper.xian.XianUserinfoMapper;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.kcis.xian.hrsync.mapper.xian", sqlSessionFactoryRef = "xianSqlSessionFactory")
public class XianDataSourceConfig {

    @Bean(name = "xianDataSource")
    @ConfigurationProperties(prefix = "spring.datasource-xian")
    public DataSource xianDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "xianSqlSessionFactory")
    public SqlSessionFactory xianSqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(xianDataSource());
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        String locationPattern = "classpath:/xml/xian/*Mapper.xml";
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources(locationPattern));
        return sqlSessionFactoryBean.getObject();
    }

    @Bean(name = "xianSqlSessionTemplate")
    public SqlSessionTemplate xianSqlSessionTemplate(@Qualifier("xianSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean
    public XianUserinfoMapper xianUserinfoMapper(@Qualifier("xianSqlSessionTemplate") SqlSessionTemplate sqlSessionTemplate) {
        return sqlSessionTemplate.getMapper(XianUserinfoMapper.class);
    }

    @Bean
    public XianCheckinoutMapper xianCheckinoutMapper(@Qualifier("xianSqlSessionTemplate") SqlSessionTemplate sqlSessionTemplate){
        return sqlSessionTemplate.getMapper(XianCheckinoutMapper.class);
    }
}
